<script setup>
/**
 * & 文件引入区域
 */
import { showImagePreview } from "vant";
import { nextTick, onMounted, reactive, ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { debounce } from "@/utils/debounce"
import {
  itemCommodityDetail,
  AddItemCommodityToCollection,
  closeItemCommodityToCollection,
  isItemCommodityToCollection,
  putItemCartById,
} from "@/server/api/itemApi";
import { addHistoryAPI } from "@/server/api/ItemCommodity";
import { getInventoryByCommodityIdAPI } from "@/server/api/shopCommodity";

import {
  userFollowItemFun,
  userUnfollowFun,
  isItemFollowFun,
  itemFansSumFun,
  shopFansNum,
  isfollow,
} from "@/hook/ItemFollow";
import { ToastFun } from "@/hook/toast";

import { useUseStore } from "@/stores/user";
import { userStore } from "@/stores/userStore";
import { messageStore } from "@/stores/message";
import { orderStatus } from "@/stores/payStore";
import { useIndexStore } from "@/stores/indexStore";
import { useCartPage } from "@/stores/cartStorePage";
import {
  deleteBuyerDataByIdAPI,
  faultAddressAIP,
  selectAllAddressAPI,
  updateBuyerDataByIdAPI,
} from "@/server/api/BuyerData";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 变量声明区
 */
const inventory = ref();
const route = useRoute();
const router = useRouter();
let userId = useUseStore().userId; // 用户id
let itemId = ref(); // 网店id
let baseUrl = useUseStore().ing; // 商品数据图片基础路径
let commodityDetail = ref(null); // 商品详情数据
let commodityId = ref(); // 商品Id
let isComToCol = ref(); // 商品收藏校验


const specsPop = ref(false)
// 当前选择的规格
const selectedSpecs = ref({});
const specsPopShowType = ref()


const skuList = ref([
  {
    "id": 89,
    "inventory": 122,
    "commodityId": "e571c99c9c3",
    "commoditySpec": {
      "颜色": "白色",
      "尺码": "M码"
    },
    "price": 111.00,
    "image": null,
    "orignPrice": 1.00,
    "piPrice": 1111.00,
    "degreeLose": 11,
    "createTime": "2024-12-16T09:20:53.000+00:00",
    "updateTime": "2024-12-16T09:20:53.000+00:00",
    "delFlag": 0
  },
  {
    "id": 90,
    "inventory": 122,
    "commodityId": "e571c99c9c3",
    "commoditySpec": {
      "颜色": "黑色",
      "尺码": "S码"
    },
    "price": 11.00,
    "image": null,
    "orignPrice": 1.00,
    "piPrice": 111.00,
    "degreeLose": 1,
    "createTime": "2024-12-16T09:20:53.000+00:00",
    "updateTime": "2024-12-16T09:20:53.000+00:00",
    "delFlag": 0
  },
  {
    "id": 91,
    "inventory": 122,
    "commodityId": "e571c99c9c3",
    "commoditySpec": {
      "颜色": "黑色",
      "尺码": "M码"
    },
    "price": 111.00,
    "image": null,
    "orignPrice": 1.00,
    "piPrice": 11.00,
    "degreeLose": 11,
    "createTime": "2024-12-16T09:20:53.000+00:00",
    "updateTime": "2024-12-16T09:20:53.000+00:00",
    "delFlag": 0
  }]); // SKU 数据

const specs = computed(() => {
  const specMap = {};
  skuList.value.forEach((sku) => {
    // 确保 commoditySpec 存在且是一个对象
    if (sku.commoditySpec && typeof sku.commoditySpec === 'object') {
      Object.entries(sku.commoditySpec).forEach(([key, value]) => {
        if (!specMap[key]) specMap[key] = new Set();
        specMap[key].add(value);
      });
    }
  });
  return Object.entries(specMap).map(([name, values]) => ({
    name,
    values: Array.from(values),
  }));
});

// 当前选择的规格文本
const selectedSpecsText = computed(() => {
  return Object.entries(selectedSpecs.value)
    .map(([key, value]) => `${key}: ${value}`)
    .join(", ") || "未选择";
});

// 匹配选择的 SKU
const selectedSku = computed(() => {
  if (Object.keys(selectedSpecs.value).length !== specs.value.length) {
    return null;
  }
  return skuList.value.find((sku) =>
    Object.entries(selectedSpecs.value).every(
      ([key, value]) => sku.commoditySpec[key] === value
    )
  );
});

// 检查当前组合是否有效，并且库存大于 0
const isSpecSelectable = (specName, value) => {
  const tempSelectedSpecs = { ...selectedSpecs.value, [specName]: value };
  return skuList.value.some((sku) => {
    return Object.entries(tempSelectedSpecs).every(
      ([key, val]) => sku.commoditySpec[key] === val
    ) && sku.inventory > 0;
  });
};

// 选择规格
const selectSpec = (specName, value) => {
  selectedSpecs.value = {
    ...selectedSpecs.value,
    [specName]: value, // 更新选中值
  };
  console.log("Selected Specs:", selectedSpecs.value);
};

const setDefaultSpecs = () => {
  const defaultSpecs = {};
  console.log(specs.value, "111")
  specs.value.forEach((spec) => {
    if (spec.values.length > 0) {
      defaultSpecs[spec.name] = spec.values[0]; // 默认选中第一个值
    }
  });
  selectedSpecs.value = defaultSpecs; // 更新选中规格
};

const specsPopShow = (type) => {
  specsPopShowType.value = type
  specsPop.value = true
  setDefaultSpecs();
}


// 添加到购物车
const addToCart = async () => {
  try {
    putItemCartReq.value.commodityId = selectedSku.value.commodityId
    putItemCartReq.value.userId = useUseStore().userId
    putItemCartReq.value.commoditySpec = Object.entries(selectedSku.value.commoditySpec).map(
      ([key, value]) => `${key}:${value}`
    );
    putItemCartReq.value.skuId = selectedSku.value.id
    ToastFun("Loading", { duration: 0 });
    let res = await putItemCartById(putItemCartReq.value);
    if (res.data.code === 200) {
      ToastFun("show", { msg: res.data.data });
      specsPop.value = false
      useCartPage().newCount++;
      showCartPop.value = false
    } else {
      ToastFun("fail", { msg: res.data.data });
    }
  } catch (error) {
    ToastFun("fail", { msg: t("item.details.NetworkError") });
  }
};

const debounceAddToCartFun = debounce(addToCart, 1000);

// 立即购买
const buyNow = () => {
  if (selectedSku.value.inventory > 0) {
    // # 将状态管理库的订单类型修改为网店类型，使得页面调用对应的接口
    orderStatus().orderType = "item";
    let avatarImag = commodityDetail.value.imagsList[0];
    // # 生成网店商品未支付订单的请求体，并且存入状态管理库
    const commoditySpec = putItemCartReq.value.commoditySpec = Object.entries(selectedSku.value.commoditySpec).map(
      ([key, value]) => `${key}:${value}`
    );
    orderStatus().itmeOrderReq = {
      uid: userId,
      buyerDataId: null,
      itemOrderDetailDTOList: [
        {
          number: putItemCartReq.value.sumCount,
          avatarImag,
          shopId: itemId.value,
          commoditySpecification: commoditySpec,
          commodityId: selectedSku.value.commodityId,
          price: selectedSku.value.price,
          discount: "",
          piPrice: selectedSku.value.piPrice,
          piAddress: commodityDetail.value.piAddress,
          skuId: selectedSku.value.id
        },
      ],
    };
    router.push({
      path: "/itemOrder",
      query: {
        commodityName: commodityDetail.value.commodityName,
      },
    });

  }
};
const debounceBuyNowtFun = debounce(buyNow, 1000);

// 加购接口请求体
let putItemCartReq = ref({
  userId: "",
  commodityId: "",
  sumCount: 1,
  commoditySpec: [],
});
const specificationList = ref([])
const selectedSpecifications = ref([])

let showBottom = ref(false); // 控制商品选择的弹出层

let showBuyPop = ref(false); // 控制商品购买弹出层
let showCartPop = ref(false); // 控制购物车弹出层

let addressList = ref(); // 获取的地址列表
let selectAddress = ref(); // 选择的地址，默认第一个
let addressId = ref(); // 选择的地址Id
let showAddressPop = ref(false); // 控制地址选择弹出层
let ecnyPrice = ref(); // 商品ecny价格
let piPrice = ref(); // 商品pi币价格
let itemImg = ref(); // 商品图片
// 初始化 itemSpecList
let itemSpecList = ref([
  { name: "颜色", data: [], selectedIndex: 0 },
  { name: "尺寸", data: [], selectedIndex: 0 },
]);
let selectitemSpec = ref(""); // 选中的商品规格
let transportList = ref([
  { text: "UPS", value: 0 },
  { text: "FeDeX", value: 1 },
  { text: "DHL", value: 2 },
]);
let transportValue = ref(0); // 运费选择

const shopInfoData = ref({}) //店铺信息
const checked = ref(null)
/**
 * & 函数区
 */
// 获取商品详情数据接口
const CommodityDetailFun = async (id) => {
  let res = await itemCommodityDetail(id);

  let data = res.data.data;
  skuList.value = data.sku
  // 图片路径拼接
  // data.shopVO.userImage = baseUrl + data.shopVO.userImage;

  commodityDetail.value = data;
  shopInfoData.value = data.shopVO

  commodityId.value = data.commodityId
  putItemCartReq.specification = data.specification

  specificationList.value = data.specification.split(',');

  checked.value = specificationList.value[0]
  console.log(specificationList.value, "规格")
  // 获取店铺id 用于用户关注
  itemId.value = data.shopVO.shopId;

  // 获取商品id 用于用户收藏
  commodityId.value = data.commodityId;

  // 调用接口判断用户是否关注该店铺,以及网店的粉丝数量
  isItemFollowFun(itemId.value, userId);
  itemFansSumFun(itemId.value);

  addHistory(commodityDetail.value.commodityId, userId); //添加历史记录
  if (data.imagsList && data.imagsList.length > 0) {
    itemImg.value = data.imagsList[0];
  } else {
    itemImg.value = undefined; // 或者不设置 itemImg.value，保持其默认值
  }
  console.log("获取商品详情数据接口", commodityDetail.value);


  // console.log("获取商品id", commodityId.value);

};


// 获取是否有库存接口
const getInventoryByCommodityId = async (shopId) => {
  const res = await getInventoryByCommodityIdAPI(shopId);
  // console.log("库存", res.data.data);
  inventory.value = res.data.data;
};

// 网店商品收藏新增接口
const AddComToColFun = async () => {
  ToastFun("Loading", {});

  let res = await AddItemCommodityToCollection({
    commodityId: commodityId.value,
    userId,
  });

  if (res.data.code == 200) {
    ToastFun("", {});
  } else {
    ToastFun("", {});
  }

  isComToCol.value = true;
  console.log("网店商品收藏", res.data.data);
};

// 校验该网店商品是否已经被收藏接口
const isComToColFun = async (obj) => {
  let res = await isItemCommodityToCollection(obj);
  // console.log("校验网店商品收藏", res.data.data);

  // 获取网店商品收藏校验
  isComToCol.value = res.data.data;
};

// 网店商品收藏删除接口
const UnComColFun = async () => {
  ToastFun("Loading", {});

  let res = await closeItemCommodityToCollection({
    userId,
    commodityId: commodityId.value,
  });

  console.log("网店商品取消收藏", res.data.data);

  if (res.data.code == 200) {
    ToastFun("", {});
    isComToCol.value = false;
  } else {
    ToastFun("", {});
  }
};

// 跳转评论页面
const goComment = () => {
  router.push({
    path: "/HomeComment",
    query: {
      commodityDetail: JSON.stringify(commodityDetail.value),
    },
  });
};

// 加入购物车接口
const putItemCartFun = async () => {

  if (checked.value !== null) {

    // 获取商品id并且修改请求体
    // putItemCartReq.commodityId = commodityId.value;
    // putItemCartReq.commoditySpec = commodityDetail.value.itemCommodityName;
    putItemCartReq.value.commodityId = commodityId.value
    putItemCartReq.value.userId = useUseStore().userId

    putItemCartReq.value.commoditySpec = checked.value
    // 请求接口
    let res = await putItemCartById(putItemCartReq.value);
    if (res.status == 200) {
      ToastFun("", {});
      useCartPage().newCount++;
      showCartPop.value = false
    } else {
      ToastFun("", {});
    }
  } else {
    ToastFun("", { msg: t("item.details.size") });
  }
};

// 跳转到订单页面
const goItemOrder = () => {

  if (checked.value !== null) {
    if (inventory.value > 0) {
      // # 将状态管理库的订单类型修改为网店类型，使得页面调用对应的接口
      orderStatus().orderType = "item";
      let avatarImag = commodityDetail.value.imagsList[0];
      // # 生成网店商品未支付订单的请求体，并且存入状态管理库
      orderStatus().itmeOrderReq = {
        uid: userId,
        buyerDataId: null,
        itemOrderDetailDTOList: [
          {
            number: putItemCartReq.value.sumCount,
            avatarImag,
            shopId: itemId.value,
            commoditySpecification: checked.value,
            commodityId: commodityDetail.value.commodityId,
            price: commodityDetail.value.price,
            discount: "",
            piPrice: commodityDetail.value.piBalance,
            piAddress: commodityDetail.value.piAddress,
          },
        ],
      };
      router.push({
        path: "/itemOrder",
        query: {
          commodityName: commodityDetail.value.commodityName,
        },
      });

    }
  } else {

    ToastFun("", { msg: t("item.details.size") });
  }
};

// 添加历史记录
const addHistory = async (commodityId, userId) => {
  const res = await addHistoryAPI(commodityId, userId);
  console.log("历史记录", res);
};

// 跳转聊天页面
const toMessage = () => {
  // 存放商品和店铺的信息，到聊天页面回显，和获取对应的itemId指定聊天

  messageStore().itemObj = {
    commodityInfo: {
      commodityId: commodityId.value,
      commodityImg: commodityDetail.value.imagsSmallList[0],
      commodityName: commodityDetail.value.itemCommodityName,
      price: commodityDetail.value.price,
    },
    itemId: itemId.value,
    itemName: commodityDetail.value.itemVO.itemName,
    itemImg: commodityDetail.value.itemVO.userImage,
  };

  router.push({
    path: "/ChatInterface",
  });
};

// 图片预览方法
const showImageFun = (images) => {
  showImagePreview({
    images,
    showIndex: false,
  });
};

// 获取用户地址列表
const getAllAddress = async () => {
  ToastFun("Loading", { duration: 1000 });
  let { data } = await selectAllAddressAPI(userId);

  if (data.code == 200) {
    if (data.data.length > 0) {
      ToastFun("", {});

      addressList.value = data.data;
      selectAddress.value = addressList.value[0];
      addressId.value = addressList.value[0].buyerDataId;

      console.log("地址列表", addressList.value);
    } else {
      ToastFun("show", { msg: "no address" });
      // router.back();
    }
  } else {
    ToastFun("", {});
    // router.back();
  }
  // console.log("选择的地址", selectAddress.value);
};

// 选择地址方法
const selectAddFun = (id) => {
  // 隐藏弹框
  addressId.value == id
    ? (showAddressPop.value = true)
    : (showAddressPop.value = false);

  // 控制样式
  addressId.value = id;
  // modifyAddress(id); //传参
  // 找到下标
  let index = addressList.value.findIndex((item) => item.buyerDataId == id);
  // 赋值选择的地址，以渲染到页面
  selectAddress.value = addressList.value[index];
  console.log("选择的地址", selectAddress.value);
};

const showCenter = ref(false);
// 定义地址列表
const addersList = ref([]);
const addFrom = ref({
  userName: "",
  address: "",
  phone: "",
});


// 定义获取地址方法
const selectAllAddress = async () => {
  const res = await selectAllAddressAPI(userId);
  // console.log(res.data.data);
  addersList.value = res.data.data;
};

// 定义修改地址发方法
const updateBuyerDataById = async (data) => {
  const res = await updateBuyerDataByIdAPI(data);
  if (res.data.code === 200) {
    selectAllAddress();
  }
};
const onSubmit = () => {
  const { address, buyerDataId, phone } = addFrom.value;
  const data = {
    address,
    buyerDataId,
    phone,
    userId,
    userName: addFrom.value.userName,
  };

  updateBuyerDataById(data);


  // 清空临时存储
  addFrom.value = {
    userName: "",
    address: "",
    phone: "",
  };



  // 关闭弹窗
  showAddressPop.value = false
  showCenter.value = false;
  ToastFun("Loading", { msg: "" });
};
// 点击修改按钮
const resAdders = (index) => {
  showCenter.value = true
  addFrom.value = index;
};
onMounted(() => {
  CommodityDetailFun(route.query.id); // 获取商品详情数据接口
  isComToColFun({
    userId,
    commodityId: route.query.id,
  }); // 校验该网店商品是否已经被收藏接口
  getAllAddress(); // 获取用户地址列表
  getInventoryByCommodityId(route.query.id); //校验是否有库存
});

const goAddShopList = () => {
  showAddressPop.value = true
}

//监听购物车
const totalPrice = computed(() => {
  return (commodityDetail.value.price * putItemCartReq.value.sumCount).toFixed(2);
});


const displayInventory = computed(() => {
  const totalInventory = commodityDetail.value.sku.reduce((sum, item) => {
    return sum + item.inventory;
  }, 0);
  return totalInventory;
});

</script>

<template>
  <div>
    <!-- 骨架屏 -->
    <div class="skeleton" v-if="!commodityDetail">
      <van-skeleton-image class="skeleton-img" />
      <van-skeleton class="skeleton-text" title :row="5" />
      <van-skeleton class="skeleton-text" title :row="5" />
      <van-skeleton class="skeleton-text" title :row="5" />
    </div>

    <div class="productsDetails" v-if="commodityDetail">
      <div class="pageTop">
        <PageTop :bg="'#fff'" :isMoreBtn="true" :isComToCol="isComToCol" @AddComToColFun="AddComToColFun"
          @UnComColFun="UnComColFun">
          <img src="/images/Home/chat.png" alt="" class="message moreBtn" @click="toMessage" />
        </PageTop>
      </div>

      <div class="swiper" dir="ltr">
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="(item, i) in commodityDetail.imagsList" :key="i">
            <img v-lazy="item" alt="" @click="showImageFun(commodityDetail.imagsList, i)" />
          </van-swipe-item>

          <template #indicator="{ active, total }">
            <div class="custom-indicator">{{ active + 1 }} / {{ total }}</div>
          </template>
        </van-swipe>
      </div>

      <div class="detailsInfo">
        <div class="priceInfo">
          <div class="topBox">
            <!-- <div class="tips">
              <div class="btn">
                <img src="/images/Home/箭头bottom_con.png" alt="" />
              </div>
              <div class="title">
                <span v-for="(item, i) in commodityDetail.couponsList" :key="i">
                  {{ item }} &nbsp;
                </span>
              </div>
            </div> -->

            <div class="mask">
            </div>
            <div class="priceBox">

              <div class="left">
                <div class="price">
                  <span>eCNY:</span>
                  <span class="num">{{ commodityDetail.sku[0].price }}</span>
                </div>
                <div class="price" style="margin-right: 10rem">
                  Pi:{{ commodityDetail.sku[0].piPrice || 0 }}
                </div>
              </div>

              <div class="stock">
                {{ $t("item.details.stock") }}
                {{ displayInventory }}
              </div>
              <div class="stock">
                Pi url:
                {{ commodityDetail.piAddress || "no" }}
              </div>
            </div>
            <div class="title">{{ commodityDetail.commodityName }}</div>
            <div class="subTitle">
              Free shipping over {{ commodityDetail.freeShippingNum }}
            </div>
          </div>

          <!-- <ForexList :bg="'#fff'" /> -->

          <div class="selectBox">
            <!-- <div class="choose item" >
            <div class="title">Choose</div>
            <div class="content">Puky Learner Bike Blue X1</div>
            <img src="/images/Home/箭头bottom.png" alt="" class="btn" />
          </div> -->

            <div class="from item">
              <div class="title">{{ $t("item.details.from") }}</div>
              <div class="content">{{ commodityDetail.originAddress }}</div>
            </div>

            <div class="to item">
              <div class="title">{{ $t("item.details.to") }}</div>
              <div class="content">
                <span v-for="(item, i) in commodityDetail.acceptAddressList" :key="i">
                  {{ item }} &nbsp;
                </span>
              </div>
              <img src="/images/Home/箭头bottom.png" alt="" class="btn" />
            </div>
          </div>

          <div class="selectBox" style="display: flex;justify-content: space-between;font-size: 20rem;"
            @click="specsPopShow('all')">
            <div>规格</div>
            <div><van-icon name="arrow" /></div>
          </div>


        </div>


        <div class="publisherBox" v-if="shopInfoData">
          <PublisherBox :type="1" :borr="8" @userFollowItemFun="userFollowItemFun(itemId)"
            @userUnfollowFun="userUnfollowFun(itemId)" :isfollow="isfollow" :data="shopInfoData" :fans="shopFansNum"
            :itemId="itemId" />
        </div>


        <div class="commentBox">
          <span>{{ $t("item.details.comment") }}</span>
          <div @click="goComment">
            <img :class="[useIndexStore().isRtl ? 'trun_180' : '']" src="/images/cart/go.png" alt="" />
          </div>
        </div>

        <div class="details">
          <div class="text">
            <div class="title">{{ $t("item.details.detail") }}</div>
            <div class="content">
              {{ commodityDetail.details || $t("item.details.data") }}
            </div>
          </div>

          <div class="img">
            <div class="title">{{ $t("item.details.parameter") }}</div>
            <img v-for="(item, i) in commodityDetail.detailImages"
              @click="showImageFun([commodityDetail.detailImages[i]])" v-lazy="item" alt="" :key="i" />
          </div>
        </div>
      </div>






      <div class="bottomBar">
        <div class="cart btn" v-if="displayInventory > 0" @click="
          specsPopShow('cart')
          ">
          {{ $t("item.details.cart") }}
        </div>

        <div class="buy btn" v-if="displayInventory > 0" @click="
          specsPopShow('buy')
          ">
          {{ $t("item.details.buy") }}
        </div>

        <div class="buy btn2" v-else @click="goItemOrder">
          {{ $t("item.details.outOfStock") }}
        </div>
      </div>
      <div class="popup">
        <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '45%' }">
          <div class="content">
            <div class="title">{{ $t("item.details.goods") }}</div>

            <div class="select">
              <div class="title">{{ $t("item.details.color") }}</div>
              <div :class="['item', i == 0 ? 'con' : '']" v-for="(item, i) in commodityDetail.colorList" :key="i">
                {{ item }}
              </div>
            </div>

            <div class="select">
              <div class="title">{{ $t("item.details.size") }}</div>
              <div :class="['item', i == 0 ? 'con' : '']" v-for="(item, i) in commodityDetail.sizeList" :key="i">
                {{ item }}
              </div>
            </div>
          </div>
        </van-popup>
      </div>
    </div>

    <!-- 规格弹出 -->
    <van-popup v-model:show="specsPop" closeable round position="bottom"
      :style="{ height: '85%', background: '#f5f5f5' }">
      <div style="height: 40rem ;"></div>
      <div class="buyPop">
        <div class="specBox">
          <van-cell-group class="to" insetn v-if="selectAddress" @click="goAddShopList()">
            <div class="text-left">
              <div class="title-to">
                <van-icon name="location-o" />
              </div>
              <div class="text-down">
                <div class="text-to">
                  <span>{{ selectAddress.userName }} &nbsp;</span>
                  <span>{{ selectAddress.phone }} &nbsp;</span>
                </div>
                <span>{{ selectAddress.address }}</span>
              </div>
            </div>
            <div class="text-right">
              <van-icon name="arrow" color="#666" />
            </div>
          </van-cell-group>
        </div>
      </div>
      <van-cell-group insetn>
        <van-card tag="标签" :price="selectedSku?.price || '请先选择规格'"
          :desc="selectedSku ? `库存: ${selectedSku.inventory}` : '未选择 SKU'" :title="commodityDetail.commodityName"
          :thumb="itemImg">
          <template #tags>
            <div>
              规格: {{ selectedSpecsText }}
            </div>
          </template>
          <template #footer>
            <van-stepper v-model="putItemCartReq.sumCount" integer min="1" max="20" />
          </template>
        </van-card>
      </van-cell-group>
      <div class="buyPop">
        <van-cell-group insetn>
          <!-- 动态渲染规格和规格值 -->
          <div v-for="(spec, specIndex) in specs" :key="specIndex" style="margin-bottom: 1.5rem;">
            <div style="font-size: 16px; font-weight: bold; margin-left: 5rem;">{{ spec.name }}</div>
            <div style="display: flex; gap: 1.5rem; flex-wrap: wrap;">
              <van-button v-for="(value, valueIndex) in spec.values" :key="valueIndex"
                :type="selectedSpecs[spec.name] === value ? 'primary' : 'default'"
                :disabled="!isSpecSelectable(spec.name, value)" @click="selectSpec(spec.name, value)" size="small"
                style="flex: 1 0 30%; max-width: 110rem; min-width: 110rem; margin-bottom: 10rem; margin-left: 10rem;">
                {{ value }}
              </van-button>
            </div>
          </div>
        </van-cell-group>
      </div>

      <div class="checkOut" v-if="specsPopShowType === 'all'">
        <div class="btn" :class="{ disabled: !selectedSku }" @click="debounceAddToCartFun">
          加入购物车
        </div>
        <div class="btn" :class="{ disabled: !selectedSku }" @click="debounceBuyNowtFun">
          立即购买
        </div>
      </div>
      <div class="checkOut" v-if="specsPopShowType === 'buy'">
        <div class="btn" @click="debounceBuyNowtFun">立即购买</div>
      </div>
      <div class="checkOut" v-if="specsPopShowType === 'cart'">
        <div class="btn" @click="debounceAddToCartFun">加入购物车</div>
      </div>
    </van-popup>

    <!--  购买弹窗功能 -->
    <van-popup v-model:show="showBuyPop" closeable round position="bottom"
      :style="{ height: '90%', background: '#f5f5f5' }">
      <div class="buyTop"></div>

      <van-cell-group insetn>
        <van-card tag="标签" :price="commodityDetail.price" :desc="commodityDetail.details"
          :title="commodityDetail.commodityName" :thumb="itemImg" origin-price="10.00">
          <!-- <template #tags>
            <div>
              规格: {{ commodityDetail.specification }}
            </div>
          </template> -->
          <template #footer>
            <van-stepper v-model="putItemCartReq.sumCount" integer min="1" max="20" />
          </template>
        </van-card>
      </van-cell-group>


      <div class="buyPop">

        <van-cell-group class="to" insetn v-if="selectAddress" @click="showAddressPop = true">
          <div class="text-left">
            <div class="title-to">
              <van-icon name="location-o" />
            </div>
            <div class="text-down">
              <div class="text-to">
                <span>{{ selectAddress.userName }} &nbsp;</span>
                <span>{{ selectAddress.phone }} &nbsp;</span>
              </div>
              <span>{{ selectAddress.address }}</span>
            </div>
          </div>

          <div class="text-right">
            <van-icon name="arrow" color="#666" />
          </div>
        </van-cell-group>

        <div class="specBox">
          <van-cell-group inset>
            <div style="font-size: 10rem;">
              <div style="margin: 10rem;">请选择规格</div>

              <!-- <van-checkbox-group v-model="selectedSpecifications" style="margin: 10rem;">
            <van-checkbox v-for="(spec, index) in specificationList" :key="index" :name="spec" style="margin: 10rem;">
              {{ spec }}
            </van-checkbox>
            <div>
            </div>
          </van-checkbox-group> -->

              <div>
                <van-radio-group v-model="checked">
                  <div v-for="(spec, index) in specificationList" :key="index"
                    style="margin-bottom: 10rem; padding-left: 10rem">
                    <van-radio :name="spec" :value="spec">{{ spec }}</van-radio>
                  </div>
                </van-radio-group>
              </div>


            </div>
          </van-cell-group>

          <van-cell-group style="font-size: 30rem">
            <!-- 动态渲染规格和规格值 -->
            <div v-for="(spec, specIndex) in specs" :key="specIndex" style="margin-bottom: 1rem;">
              <div style="font-size: 30rem">{{ spec.name }}</div>
              <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                <van-button v-for="(value, valueIndex) in spec.values" :key="valueIndex"
                  :type="selectedSpecs[specIndex] === value ? 'primary' : 'default'"
                  @click="selectSpec(specIndex, value)" size="small">
                  {{ value }}
                </van-button>
              </div>
            </div>

            <!-- 显示 SKU 匹配结果 -->
            <div v-if="filteredSkuList.length > 0" style="margin-top: 1rem;">
              <div v-for="(sku, index) in filteredSkuList" :key="index" style="margin-bottom: 1rem;">
                <van-checkbox v-model="sku.selected">{{ sku.commoditySpec }} - ￥{{ sku.price }}</van-checkbox>
              </div>
            </div>
            <div v-else style="margin-top: 1rem; color: gray; text-align: center;">
              暂无匹配的 SKU 组合
            </div>

            <!-- 提交按钮 -->
            <van-button type="success" size="large" block @click="handleSelectedSkus">
              确定选择
            </van-button>
          </van-cell-group>

        </div>

        <van-cell-group class="transport" insetn>
          <label class="">运送方式：</label>
          <van-dropdown-menu class="transport-menu">
            <van-dropdown-item v-model="transportValue" :options="transportList" />
          </van-dropdown-menu>
        </van-cell-group>

        <van-cell-group class="transport" insetn>
          <label>运费：</label>
        </van-cell-group>
      </div>
      <div class="checkOut">
        <div class="total">{{ $t("cart.total") }}：<span>{{ totalPrice }}</span></div>

        <div class="btn" @click="goItemOrder">立即支付</div>
      </div>
    </van-popup>

    <!--  购物车弹窗功能 -->
    <van-popup v-model:show="showCartPop" closeable round position="bottom"
      :style="{ height: '60%', background: '#f5f5f5' }">
      <div class="buyTop"></div>

      <van-cell-group insetn>
        <van-card tag="标签" :price="commodityDetail.price" :desc="commodityDetail.details"
          :title="commodityDetail.commodityName" :thumb="itemImg" origin-price="10.00">

          <template #footer>
            <van-stepper v-model="putItemCartReq.sumCount" integer min="1" max="20" />
          </template>
        </van-card>
      </van-cell-group>

      <van-cell-group inset>
        <div style="font-size: 10rem;">
          <div style="margin: 10rem;">请选择规格</div>
          <div>
            <van-radio-group v-model="checked">
              <div v-for="(spec, index) in specificationList" :key="index"
                style="margin-bottom: 10rem; padding-left: 10rem">
                <van-radio :name="spec" :value="spec">{{ spec }}</van-radio>
              </div>
            </van-radio-group>
          </div>
        </div>
      </van-cell-group>

      <van-cell-group style="font-size: 30rem">
        <!-- 动态渲染规格和规格值 -->
        <div v-for="(spec, specIndex) in specs" :key="specIndex" style="margin-bottom: 1rem;">
          <div style="font-size: 30rem">{{ spec.name }}</div>
          <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
            <van-button v-for="(value, valueIndex) in spec.values" :key="valueIndex"
              :type="selectedSpecs[specIndex] === value ? 'primary' : 'default'" @click="selectSpec(specIndex, value)"
              size="small">
              {{ value }}
            </van-button>
          </div>
        </div>

        <!-- 显示 SKU 匹配结果 -->
        <div v-if="filteredSkuList.length > 0" style="margin-top: 1rem;">
          <div v-for="(sku, index) in filteredSkuList" :key="index" style="margin-bottom: 1rem;">
            <van-checkbox v-model="sku.selected">{{ sku.combination }} - ￥{{ sku.price }}</van-checkbox>
          </div>
        </div>
        <div v-else style="margin-top: 1rem; color: gray; text-align: center;">
          暂无匹配的 SKU 组合
        </div>

        <!-- 提交按钮 -->
        <van-button type="success" size="large" block @click="handleSelectedSkus">
          确定选择
        </van-button>
      </van-cell-group>



      <div class="checkOut">
        <div class="total">{{ $t("cart.total") }}：<span>{{ totalPrice }}</span></div>
        <div class="btn" @click="putItemCartFun">加入购物车</div>
      </div>
    </van-popup>
    <!-- 弹出层选择地址 -->
    <div class="popup" v-if="orderStatus().orderType === 'item'">
      <van-popup v-model:show="showAddressPop" position="bottom" :style="{ height: '45%' }">
        <ul class="addersList">
          <li :class="[item.buyerDataId == addressId ? 'border' : '']" @click="selectAddFun(item.buyerDataId)"
            v-for="item in addressList" :key="item.buyerDataId">
            <p class="ellipsis-2">{{ item.address }}</p>

            <div class="footer_en">
              <div class="info">
                <div class="name">{{ item.userName }}</div>
                <div class="date">{{ item.phone }}</div>
              </div>
              <div class="update" @click="resAdders(item)">
                {{ $t("me.modify") }}
              </div>
            </div>
          </li>
        </ul>
      </van-popup>
    </div>
  </div>

  <!-- 选择地址弹窗 -->
  <div class="popup">
    <van-popup v-model:show="showAddressPop" position="bottom" :style="{ height: '45%' }">
      <ul class="addersList">
        <li :class="[item.buyerDataId == addressId ? 'border' : '']" @click="selectAddFun(item.buyerDataId)"
          v-for="item in addressList" :key="item.buyerDataId">
          <p class="ellipsis-2">{{ item.address }}</p>

          <div class="footer_en">
            <div class="info">
              <div class="name">{{ item.userName }}</div>
              <div class="date">{{ item.phone }}</div>
            </div>
            <div class="update" @click="resAdders(item)">
              {{ $t("me.modify") }}
            </div>
          </div>
        </li>
      </ul>
    </van-popup>
  </div>

  <!-- 修改地址弹窗 -->
  <van-popup v-model:show="showCenter" class="modify" round>
    <van-form>
      <van-cell-group inset>
        <van-field name="name" :label="$t('me.addNewAddress.name')" :placeholder="$t('me.addNewAddress.name')"
          v-model="addFrom.userName" :rules="[
            {
              required: true,
              message: $t('me.addNewAddress.name'),
            },
          ]" />

        <van-field type="text" name="address" v-model="addFrom.address" :label="$t('me.addNewAddress.address')"
          :placeholder="$t('me.addNewAddress.address')" :rules="[
            {
              required: true,
              message: $t('me.addNewAddress.address'),
            },
          ]" />

        <van-field v-model="addFrom.phone" name="phone" type="phone" :label="$t('me.addNewAddress.phone')"
          :placeholder="$t('me.addNewAddress.phone')" :rules="[
            {
              required: true,
              message: $t('me.addNewAddress.phone'),
            },
          ]" />
      </van-cell-group>

      <div style="margin: 16rem">
        <div class="modifyBtn" @click="onSubmit">
          确认
        </div>
      </div>
    </van-form>
  </van-popup>
</template>

<style lang="scss" scoped>
.skeleton {
  box-sizing: border-box;
  overflow: hidden;

  padding-top: 30rem;
  max-height: 100vh;

  >div {
    margin-bottom: 20rem;
  }

  >.skeleton-img {
    width: 320rem;
    height: 280rem;
    margin: 0 auto 20rem;
  }
}

.productsDetails {
  background: #f5f5f5;
  position: relative;

  max-height: 100vh;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  >.pageTop {
    position: fixed;
    z-index: 30;
    top: 0rem;
    left: 0rem;
    right: 0rem;

    .message {
      width: 24rem;
      margin: 0 12rem;
    }
  }

  >.swiper {
    background: #fff;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;

    .van-swipe-item {
      display: flex;
      align-items: center;
      min-height: 323rem;

      img {
        width: 323rem;
        height: 323rem;
        margin: 0 auto;
      }
    }

    .custom-indicator {
      position: absolute;
      right: 16rem;
      bottom: 55rem;

      width: 35rem;
      height: 20rem;
      font-size: 11rem;
      line-height: 20rem;
      text-align: center;
      background: #e6e6e6;

      color: rgba(102, 102, 102, 1);
    }
  }

  >.detailsInfo {
    margin-top: 280rem;

    >.priceInfo {
      margin: 0rem 16rem;

      >.topBox {
        position: relative;
        border-radius: 0 0 12rem 12rem;

        >.tips {
          display: flex;
          align-items: center;
          padding: 10rem 0 20rem;
          border-radius: 12rem 12rem 0 0;

          position: absolute;
          left: 0;
          right: 0;
          background: #d0c0dd;

          img {
            width: 6rem;
            height: 4rem;
            margin: 0 12rem 2rem 16rem;
          }

          >.title {
            font-size: 12rem;
            line-height: 18rem;
            font-weight: 400;
          }
        }

        >.mask {
          height: 28rem;
        }

        >.priceBox {
          position: relative;
          z-index: 10;
          background: #fff;

          display: flex;
          align-items: center;
          justify-content: space-between;

          padding: 12rem 12rem 2rem;
          border-radius: 12rem 12rem 0 0;

          >.left {
            display: flex;
            flex-direction: column;

            .price {
              color: #642e8e;
              font-weight: 500;
              line-height: 40rem;
              font-size: 20rem;

              span.num {
                font-size: 28rem;
                margin-left: 8rem;
                margin-right: 8rem;
              }
            }

            .oldPrice {
              font-size: 16rem;
              font-weight: 400;
              line-height: 28rem;
              color: #999999;

              span.num {
                font-size: 20rem;
                margin: 0 5rem;
                text-decoration: line-through;
              }
            }
          }

          >.stock {
            font-size: 12rem;
            color: #999;
          }
        }

        >.title,
        >.subTitle {
          position: relative;
          z-index: 10;
          padding: 0 12rem 2rem;
          background: #fff;
        }

        >.title {
          padding-right: 20rem;
          font-size: 16rem;
          line-height: 24rem;
          font-weight: 400;
          color: #666666;
        }

        .subTitle {
          font-size: 12rem;
          line-height: 24rem;
          padding-bottom: 12rem;
          font-weight: 400;
          color: #cccccc;

          border-radius: 0 0 12rem 12rem;
        }
      }

      >.selectBox {
        position: relative;
        z-index: 10;
        margin: 8rem 0;
        background: #fff;
        border-radius: 12rem;
        padding: 12rem;
        padding-right: 10rem;

        >.item {
          position: relative;
          display: flex;
          align-items: center;
          margin-bottom: 4rem;

          font-size: 12rem;
          line-height: 16rem;
          color: #999999;

          .btn {
            width: 8rem;
            height: auto;
            position: absolute;
            right: 14rem;

            .btn.disabled {
              background-color: #ccc;
              pointer-events: none;
              cursor: not-allowed;
            }
          }

          >.title {
            color: #666666;
            min-width: 50rem;
            margin-right: 12rem;

            font-size: 14rem;
            line-height: 24rem;
          }

          >.content {
            padding-right: 30rem;
          }
        }
      }
    }

    .publisherBox {
      margin: 12rem 15rem 12rem 17rem;
    }

    >.details {
      padding: 12rem 16rem 100rem;
      background: #fff;
      position: relative;
      z-index: 10;

      .title {
        color: #333;
        font-size: 20rem;
        line-height: 20rem;
        font-weight: 500;
        margin-bottom: 12rem;
      }

      >.text {
        margin-bottom: 10rem;

        >.content {
          font-size: 14rem;
          line-height: 16rem;
          font-weight: 400;
          color: #999;
        }
      }

      >.img {
        width: 100%;

        >img {
          width: 100%;
        }
      }
    }

    >.commentBox {
      padding: 20rem 16rem;
      height: 25rem;

      display: flex;
      align-items: center;
      justify-content: space-between;

      background: #f5f5f5;

      position: relative;
      z-index: 10;

      span {
        font-size: 16rem;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);
        margin-left: 16rem;
      }

      div {
        display: flex;
        align-items: center;
        justify-content: center;

        width: 24rem;
        height: 24rem;
        line-height: 24rem;

        img {
          width: 6rem;
          height: 12rem;
        }
      }
    }
  }

  >.bottomBar {
    padding: 6rem 16rem;
    background: #fff;

    position: fixed;
    z-index: 30;
    left: 0;
    right: 0;
    bottom: 0;

    display: flex;
    justify-content: space-between;

    >.btn {
      width: 170rem;
      padding: 11rem 0 10rem;

      text-align: center;
      font-size: 16rem;
      line-height: 22rem;
      font-weight: 400;

      border-radius: 22rem;

      &.cart {
        color: #642e8e;
        border: 1rem solid #642e8e;
      }

      &.buy {
        background: #642e8e;
        color: #fff;
      }
    }

    >.btn2 {
      padding: 11rem 0 10rem;
      text-align: center;
      font-size: 16rem;
      line-height: 22rem;
      font-weight: 400;

      flex: 1;

      border-radius: 22rem;

      &.cart {
        color: #642e8e;
        border: 1rem solid #642e8e;
        margin-right: 8rem;
      }

      &.buy {
        background: #eee01b;
        color: #fff;
      }
    }
  }

  >.popup {
    :deep(.van-popup.van-popup--bottom) {
      border-radius: 15rem 15rem 0 0;

      &::-webkit-scrollbar {
        display: none;
      }
    }

    .content {
      padding: 20rem 16rem 0;

      >.title {
        padding-bottom: 5rem;
        font-size: 20rem;
        line-height: 20rem;
        font-weight: 500;
      }

      >.select {
        display: flex;
        flex-wrap: wrap;

        font-size: 16rem;
        border-bottom: 1rem solid #e7ddee88;
        padding: 10rem 0 15rem;

        >.title {
          width: 100%;
          padding: 5rem 0 10rem;
        }

        >.item {
          padding: 8rem 10rem;
          background: #f5f5f5;

          border-radius: 10rem;
          margin: 0 10rem 5rem;

          font-size: 14rem;
          line-height: 14rem;

          &.con {
            background: #d0c0dd;
            color: #fff;
          }
        }
      }
    }
  }
}

.popup {
  :deep(.van-popup) {
    border-radius: 15rem 15rem 0 0;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .addersList {
    padding-top: 20rem;

    li {
      border: 1rem solid #ccc;
      box-sizing: border-box;
      width: 90%;
      background-color: #ffffff;
      border-radius: 10rem;
      margin: 10rem auto 15rem;
      padding: 10rem 15rem;

      p {
        width: 70%;
        font-size: 16rem;
        line-height: 30rem;
      }

      .footer_en {
        display: flex;
        justify-content: space-between;

        .info {
          color: #ccc;
          display: flex;
          font-size: 16rem;
          line-height: 30rem;

          .name {
            margin-right: 10rem;
          }
        }

        .update {
          max-width: 70rem;
          white-space: nowrap;

          color: #fff;
          padding: 0rem 20rem;
          background: #642e8eff;
          border: 2rem solid;
          border-radius: 5rem;
          font-size: 15rem;
        }

        .text_right {
          width: 58rem;
          height: 36rem;
          text-align: center;
          line-height: 36rem;
          white-space: nowrap;
          color: #642e8eff;
          border: 1rem solid;
          border-radius: 5rem;
        }
      }

      &.border {
        border: 1rem solid #642e8eff;
      }
    }
  }
}

.buyTop {
  height: 60rem;
  background: #efe7f7;
}

.item {
  display: flex;
  // font-size: 12rem;
  align-items: center;
  border-radius: 10rem;
  top: -10rem;
  padding: 10rem 10rem;

  .item-img {
    width: 100;
    height: 100;
  }

  .item-price {
    display: flex;
    flex-direction: column;
    margin: 0 20rem;
    color: #642e8e;
    font-weight: 500;
    line-height: 40rem;
    font-size: 20rem;

    span.num {
      font-size: 28rem;
      margin-left: 8rem;
      margin-right: 8rem;
    }

    .buy-num {
      font-size: 12rem;
    }
  }
}

.buyPop {
  padding: 0 5rem;

  .to {
    display: flex;
    // font-size: 12rem;
    top: -3rem;
    align-items: center;
    padding: 10rem 5rem;
    justify-content: space-between;
    border-radius: 10rem;
    margin-bottom: 5rem;

    .text-left {
      display: flex;
      align-items: center;

      .title-to {
        color: #666;
        font-size: 23rem;
      }

      .text-down {
        font-size: 16rem;
        color: #666;
        margin-left: 12rem;

        .text-to {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }
    }

    .text-right {
      font-size: 20rem;
      color: #666;
    }
  }

  .specBox {
    .spec {
      // font-size: 12rem;
      align-items: center;
      padding: 10rem 5rem;
      //border-radius: 10rem;
      //margin: 5rem 0;

      .spec-title {
        font-size: 18rem;
        color: #000000;
        margin-left: 5rem;
      }

      .spec-content {
        display: flex;
        align-items: center;

        .spec-item {
          font-size: 16rem;
          border: 1rem solid #f3f1f1;
          border-radius: 5rem;
          margin: 5rem 5rem;
          color: #202020;
          background: #f5f3f3;
          padding: 5rem 5rem;
        }

        .active {
          background: #642e8eff;
          color: #fff;
        }
      }
    }
  }

  .transport {
    display: flex;
    align-items: center;
    font-size: 16rem;
    padding: 10rem 5rem;
    // justify-content: space-between;
    --van-dropdown-menu-background: #fff;
    --van-dropdown-menu-item-active-color: #642e8eff;
    --van-dropdown-menu-height: 30rem;
    --van-dropdown-menu-shadow: none;
    //--van-dropdown-menu-title-text-color: #642e8eff;
    --van-dropdown-menu-title-active-text-color: #642e8eff;
    //--van-dropdown-menu-title-disabled-text-color: #642e8eff;
    --van-dropdown-menu-option-active-color: #642e8eff;
    --van-dropdown-menu-option-disabled-color: #642e8eff;

    .title {
      color: red;
      font-size: 18rem;
    }

    .transport-menu {
      margin: auto;
    }
  }
}

.checkOut {
  width: 100%;
  height: 60rem;
  bottom: 0rem;
  background-color: #fff;
  position: fixed;
  display: flex;
  border-radius: 10rem;
  align-items: center;
  justify-content: space-around;

  .total {
    margin-left: 18rem;
    font-size: 16rem;
    color: rgba(51, 51, 51, 1);

    span {
      font-size: 16rem;
      font-weight: 600;
    }
  }

  .btn {
    border-radius: 27rem;
    width: 150rem;
    background: rgba(100, 46, 142, 1);
    color: rgba(255, 255, 255, 1);
    line-height: 36rem;
    font-size: 14rem;
    right: 12rem;
    padding: 5rem 30rem;
    text-align: center;
  }
}

.modify {
  padding-top: 10rem;
  border-radius: 10rem;

  .modifyBtn {
    font-size: 22rem;
    margin: 0 15%;
    border-radius: 20rem;
    text-align: center;
    padding: 3rem 0;

    background: #642e8e;
    color: #fff;

  }
}

.van-button[disabled] {
  background-color: #e5e5e5 !important;
  color: #999 !important;
  border-color: #e5e5e5 !important;
}
</style>
